package com.dean.utils;

import com.dean.action.CsvOptAction;
import com.dean.exception.DeanRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ShellScExecUtils {
    private final Logger logger = LoggerFactory.getLogger(CsvOptAction.class);
    public void exec(String command,int timeout){
        ProcessBuilder processBuilder = new ProcessBuilder(command.split("\\s+"));
        processBuilder.redirectErrorStream(true);
        Process process = null;
        BufferedReader reader = null;
        try {
            process = processBuilder.start();
            // 超时时间转化为毫秒
            timeout = timeout*1000;
            long startTime = System.currentTimeMillis();
            long elapsedTime = 0L;
            while (elapsedTime < timeout && process.isAlive()) {
                elapsedTime = System.currentTimeMillis() - startTime;
            }
            if (process.isAlive()) {
                process.destroy();
                throw new DeanRuntimeException(999,"Process timed out and was destroyed.");
            } else {
                reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    logger.info(line);
                }
                if("SUCCESSFUL".equals(line)){
                    throw new DeanRuntimeException(999,"shell script exec failed67");
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            throw new DeanRuntimeException(999,e.getMessage());
        }finally {
            if(process.isAlive()){
                process.destroy();
            }
        }


    }
}
